package com.kele.pay.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.kele.common.model.response.Result;
import com.kele.pay.service.WxPayService;
import com.kele.pay.service.WxPayService_RestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.Map;

@RestController
@RequestMapping("wxpay")
public class WxPayController {

    @Autowired
    WxPayService payService;

    @Autowired
    WxPayService_RestTemplate wxPayService_restTemplate;

    @GetMapping("unifiedOrder/{orderId}/{total_fee}/{body}")
    public Result unifiedOrder(@PathVariable Long orderId,
                               @PathVariable Integer total_fee,
                               @PathVariable(required = false) String body) throws Exception {

        return payService.unifiedOrder(orderId,
               total_fee,
               body);
    }

    @Autowired
    HttpServletRequest request;
    @GetMapping("notifyOrder")
    public Result notifyOrder() throws Exception {
        BufferedReader reader = request.getReader();

        StringBuilder stringBuilder = new StringBuilder();
        String line = "";

        while ((line = reader.readLine())!=null){
            stringBuilder.append(line);
        }
        String xml_body = stringBuilder.toString();

        Map<String, String> stringStringMap = WXPayUtil.xmlToMap(xml_body);

        String return_code = stringStringMap.get("return_code");
        String return_msg = stringStringMap.get("return_msg");

        if(!StringUtils.isEmpty(return_code) && return_code.equals("SUCCESS")){
            String out_trade_no = stringStringMap.get("out_trade_no");
            System.out.println("notifyOrder:" + out_trade_no);
        }
        System.out.println("notifyOrder");
        return Result.SUCCESS();
    }

    @GetMapping("orderQuery/{orderId}")
    public Result orderQuery(@PathVariable Long orderId) throws Exception {

        return payService.orderQuery(orderId);
    }

}
